package com.example.demo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.PlatMapper;
import com.example.demo.dao.Project_detailsMapper;
import com.example.demo.dao.SysuserMapper;
import com.example.demo.domain.PageBean;
import com.example.demo.domain.Plat;
import com.example.demo.domain.ProcessinstanceFile;
import com.example.demo.domain.ProcessinstanceFileHistory;
import com.example.demo.domain.Project_details;
import com.example.demo.domain.Sysuser;
import com.example.demo.services.ActivitiService;
import com.example.demo.services.PlatService;
import com.example.demo.util.FileUtils;
import com.example.demo.util.Util;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/activiti")
public class ActivitiController {

	private static Logger logger = Logger.getLogger(ActivitiController.class);

	@Autowired
	private SysuserMapper sysuserMapper;
	@Autowired
	private ActivitiService activitiService;
	@Autowired
	private Project_detailsMapper project_detailsMapper;

	/**
	 * 查询任务列表
	 * 
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/taskList")
	public String taskList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = new JSONObject();

		// 从会话中取出用户信息
		Object username = SecurityUtils.getSubject().getPrincipal();
		// 查询用户名称
		Sysuser sysuser = sysuserMapper.findByName(username.toString());

		map.put("name", request.getParameter("nameText"));
		map.put("processInstanceId", request.getParameter("numberText"));
		map.put("pageNum", request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page")));
		map.put("pageSize", request.getParameter("limit") == null ? 10000 : Integer.parseInt(request.getParameter("limit")));
		map.put("isProcessInstanceRead", request.getParameter("isProcessInstanceRead"));
		try {
			if (sysuser.getRole_id() != 1) {
				map.put("user_id", sysuser.getId());
				PageBean<Map<String, Object>> pb = activitiService.taskList(map);
				obj.put("data", pb.getList());
				obj.put(Util.COUNT, pb.getTotalRecord());
				obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
				obj.put(Util.MESSAGE, "查询任务列表成功！");
			} else {
				PageBean<Map<String, Object>> pb = activitiService.taskList(map);
				obj.put("data", pb.getList());
				obj.put(Util.COUNT, pb.getTotalRecord());
				obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
				obj.put(Util.MESSAGE, "查询任务列表成功！");
			}
		} catch (Exception e) {
			logger.error("=============[ActivitiController[taskList[查询任务列表失败]]]==========", e);
		}
		return obj.toString();
	}

	/**
	 * 完成任务
	 * 
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/finishTask")
	public String finishTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = new JSONObject();

		// 从会话中取出用户信息
		Object username = SecurityUtils.getSubject().getPrincipal();
		// 查询用户名称
		Sysuser sysuser = sysuserMapper.findByName(username.toString());
		
		try {
			map.put("user_id", sysuser.getId());
			map.put("task_id", request.getParameter("task_id"));
			map.put("approval", request.getParameter("approval"));
			map.put("node_name", request.getParameter("node_name"));
			map.put("remarks", request.getParameter("remarks"));
			map.put("assignee", request.getParameter("assignee"));
			map.put("processInstanceId", request.getParameter("processInstanceId"));
			map = activitiService.finishTask(map);
			obj.put(Util.RESULT, map.get("code"));
			obj.put(Util.MESSAGE, map.get("msg"));
		} catch (Exception e) {
			logger.error("=============[ActivitiController[finishTask[完成任务失败]]]==========", e);
		}
		return obj.toString();
	}

	/**
	 * 新建项目
	 * 
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/newProject")
	public String newProject(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = new JSONObject();

		// 从会话中取出用户信息
		Object username = SecurityUtils.getSubject().getPrincipal();
		// 查询用户名称
		Sysuser sysuser = sysuserMapper.findByName(username.toString());

		// 项目数据
		map.put("project_name", request.getParameter("project_name"));
		map.put("type_id", request.getParameter("type_id"));
		map.put("projectId", request.getParameter("projectId"));
		map.put("type", request.getParameter("tpye"));
		map.put("user_id", sysuser.getId());
		try {
			map = activitiService.newProject(map);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "新增项目成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[newProject[新建项目失败]]]==========", e);
		}
		return obj.toString();
	}

	/**
	 * 查询历史项目
	 * 
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/historyProjectList")
	public String historyProjectList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = new JSONObject();

		String timeText = request.getParameter("timeText");
		System.out.println(timeText);
		if(timeText != null && !"".equals(timeText)) {
			map.put("start_time", timeText.substring(0, 10));
			map.put("end_time",  timeText.substring(12));
		}
		map.put("name", request.getParameter("nameText"));
		map.put("processInstanceId", request.getParameter("numberText"));
		map.put("type_id", request.getParameter("type_id"));
		map.put("pageNum", Integer.parseInt(request.getParameter("page")));
		map.put("pageSize", Integer.parseInt(request.getParameter("limit")));
		int pageSize = Integer.parseInt(request.getParameter("limit"));
		int pageNum = Integer.parseInt(request.getParameter("page"));
		
		//查询历史数据、可能和个人相关、流程实例相关、或者全类型项目
		try {
			List<Map <String, Object>> pb = activitiService.historyProjectList(map);
			obj.put(Util.COUNT, pb.size());
			obj.put("data", pb.subList(pageSize*(pageNum-1), pb.size() < pageSize*pageNum ? pb.size() : pageSize*pageNum));			
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询历史项目！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[historyProjectList[查询历史项目]]]==========", e);
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "查询历史项目！");
		}
		return obj.toString();
	}
	
	/**
	 * 查询项目操作记录
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/operationRecord")
	public String operationRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		JSONObject obj = new JSONObject();	
		String processInstanceId = request.getParameter("processInstanceId");
		//查询历史数据、可能和个人相关、流程实例相关、或者全类型项目
		try {
			result = activitiService.operationRecord(processInstanceId);
			obj.put("data", result);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询项目操作记录成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[operationRecord[查询项目操作记录]]]==========", e);
		}
		return obj.toString();
	}
	
	/**
	 * 删除项目
	 * 
	 * @author hc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/delectExample")
	public String delectExample(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = new JSONObject();
		
		map.put("processInstanceId", request.getParameter("processInstanceId"));
		
		try {
			activitiService.delectExample(map);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "删除项目成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[delectExample[删除项目成功]]]==========", e);
		}
		return obj.toString();
	}
	
	/**
	 * 添加变量
	 * 
	 * @author dsh
	 * @param variables taskId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/addVariables")
	@ResponseBody
	public Object addVariables(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = (String) map.get("taskId");
		String processInstanceId = (String) map.get("processInstanceId");	
		@SuppressWarnings("unchecked")
		Map<String, Object> variables = (Map<String, Object>) map.get("variables");	
		System.out.println(map);
		try {
			activitiService.addVariables(variables, taskId, processInstanceId);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "添加变量成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[addVariables[添加变量成功！]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 添加附件
	 * 
	 * @author dsh
	 * @param variables taskId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/addAttachments")
	@ResponseBody
	public Object addAttachments(@RequestBody Map<String, Object> map ,  HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = (String) map.get("taskId");
		String processInstanceId = (String) map.get("processInstanceId");
		@SuppressWarnings("unchecked")
		Map<String, Object> attachments = (Map<String, Object>) map.get("attachments");	
		try {
			activitiService.addAttachments(attachments, taskId, processInstanceId);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "添加附件成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[addAttachments[添加附件成功]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 完成任务two
	 * 
	 * @author dsh
	 * @param variables taskId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/finishTaskTwo")
	@ResponseBody
	public Object finishTaskTwo(@RequestBody Map<String, Object> map ,  HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		try {
			activitiService.finishTaskTwo(map);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "完成任务成功！");
		} catch (Exception e) {
			logger.error("=============[ActivitiController[addAttachments[完成任务失败]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 查找历史节点记录数据
	 * 
	 * @author dsh
	 * @param processInstanceId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/findProcessInstanceHistoryRecord")
	@ResponseBody
	public Object findProcessInstanceHistoryRecord(@RequestBody Map<String, Object> map ,  HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String processInstanceId = (String) map.get("processInstanceId");
		try {
			// 从会话中取出用户信息
			Object username = SecurityUtils.getSubject().getPrincipal();
			// 查询用户名称
			Sysuser sysuser = sysuserMapper.findByName(username.toString());
			List<Map<String, Object>> result = activitiService.findProcessInstanceHistoryRecord(processInstanceId);
			obj.put("data", result);
			obj.put("userId", sysuser.getId());
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查找历史节点记录成功！");
		} catch (Exception e) {
			obj.put("data", "");
			logger.error("=============[ActivitiController[addAttachments[查找历史节点记录失败]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 	查找taskId的所有附件
	 * @author dsh
	 * @param taskId
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/findTaskAttachmentsTable")
	@ResponseBody
	public Object findTaskAttachmentsTable(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
		try {
			List<Attachment> result = activitiService.findTaskAttachmentsTable(taskId);
			obj.put("data", result);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查找历史节点记录成功！");
		} catch (Exception e) {
			obj.put("data", "");
			logger.error("=============[ActivitiController[addAttachments[查找历史节点记录失败]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 	根据Id删除附件
	 * @author dsh
	 * @param taskId
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/deleteAttachmentById")
	@ResponseBody
	public Object deleteAttachmentById(HttpServletRequest request, HttpServletResponse response, @RequestBody  Map<String, Object> map  ) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		List<LinkedHashMap> attachments = (List<LinkedHashMap>) map.get("attachments");
		System.out.println(attachments.toString());
		try {
			for(int i = 0; i < attachments.size(); i++) {
				LinkedHashMap attachment = attachments.get(i);
				if(FileUtils.deleteFile((String)attachment.get("url"))) {
					activitiService.deleteAttachmentById((String)attachment.get("id"));					
				}
			}	
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "删除附件成功！");
		} catch (Exception e) {
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "删除附件失败！");
			logger.error("=============[ActivitiController[addAttachments[删除附件失败]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 	查询此流程实例关联的所有全局文件
	 * @author dsh
	 * @param processInstanceId 流程实例ID
	 * @return List<ProcessinstanceFile>
	 */
	@RequestMapping(value = "/findGlobalFIleTableByPid")
	@ResponseBody
	public Object findGlobalFIleTableByPid(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();		
		try {
			String processInstanceId = request.getParameter("processInstanceId") == null ? "" : request.getParameter("processInstanceId");
			if(!processInstanceId.equals("")) {
				List<ProcessinstanceFile> 	processinstanceFiles  =  activitiService.findGlobalFIleByPid(processInstanceId);	
				obj.put("data", processinstanceFiles);
			}else {
				obj.put("data", "");
			}
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询全局文件成功！");
		} catch (Exception e) {
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "查询全局文件失败！");
			logger.error("=============[ActivitiController[addAttachments[查询全局文件失败]]]==========", e);
		}
		return obj;
	}
	
	
	/**
	 * 	查询此流程实例关联的所有全局文件
	 * @author dsh
	 * @param processInstanceFileId 流程实例ID
	 * @return List<ProcessinstanceFile>
	 */
	@RequestMapping(value = "/findSingleGlobalFIleHisTableById")
	@ResponseBody
	public Object findSingleGlobalFIleHisTableById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();		
		try {
			String processInstanceFileId = request.getParameter("processInstanceFileId") == null ? "" : request.getParameter("processInstanceFileId");
			if(!processInstanceFileId.equals("")) {
				List<Map<String, Object>> 	ProcessinstanceFileHistories  =  activitiService.findSingleGlobalFIleHisById(processInstanceFileId);
				obj.put("data", ProcessinstanceFileHistories);
			}else {
				obj.put("data", "");
			}
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询全局文件成功！");
		} catch (Exception e) {
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "查询全局文件失败！");
			logger.error("=============[ActivitiController[addAttachments[查询全局文件失败]]]==========", e);
		}
		return obj;
	}
	
	
	@RequestMapping(value = "/findRejectStatusByTaskId")
	@ResponseBody
	public Object findRejectStatusByTaskId(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();		
		try {
			String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
			if(!taskId.equals("")) {
				//boolean 	result  =  activitiService.findRejectStatusByTaskId(taskId);
				boolean isDepartment = activitiService.findIsDepartment(taskId);
				//obj.put("data", result);
				obj.put("isDepartment", isDepartment);
			}else {
				//obj.put("data", "");
				obj.put("isDepartment", false);
			}
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询全局文件成功！");
		} catch (Exception e) {
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "查询全局文件失败！");
			logger.error("=============[ActivitiController[addAttachments[查询全局文件失败]]]==========", e);
		}
		return obj;
	}
	
	
	/*判断平台名称或者编号是否存在**/   
	@RequestMapping("/isProjectDetailsNameExist")
	@ResponseBody
	public Object isProjectDetailsNameExist(HttpServletRequest request, String project_name) {
		Map<String,Object> obj = new HashMap<String,Object>();//传递给后台的对象
		String data = "0 ";	
		try {		
			List<Project_details> project_detailsList = project_detailsMapper.findAll();
			if(project_detailsList.size() > 0) {
				for(Project_details project_details: project_detailsList) {
					if(project_details.getName().equals(project_name)) {
						data = "1";
						break;
					}
				}
			}			
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查询历史版本成功！");
			obj.put("data", data);
		}catch (Exception e) {
			logger.error(e);
			obj.put("data", "2");
			obj.put(Util.RESULT, Util.RESULT_RC_EXCEPTION);
			obj.put(Util.MESSAGE, "查询历史版本失败！");
			logger.error("=============[PlatController[isPlatNameExist[]]]==========", e);
		}				
		return obj;
	}
	
	/**
	 * 	查找下一节点的名称
	 * @author dsh
	 * @param taskId
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/getNextTaskName")
	@ResponseBody
	public Object getNextTaskName(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
		try {
			Map<String, Object> result = activitiService.getNextTaskName(taskId);
			obj.put("data", result);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查找历史节点记录成功！");
		} catch (Exception e) {
			obj.put("data", "");
			logger.error("=============[ActivitiController[addAttachments[查找历史节点记录失败]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 	查找下一节点的名称
	 * @author dsh
	 * @param taskId
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/isUploadFile")
	@ResponseBody
	public Object isUploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
		try {
			boolean result = activitiService.findIsUpload(taskId);
			obj.put("data", result);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查找历史节点记录成功！");
		} catch (Exception e) {
			obj.put("data", "");
			logger.error("=============[ActivitiController[addAttachments[查找历史节点记录失败]]]==========", e);
		}
		return obj;
	}
	
	
	/**
	 * 	查找任务所有变量
	 * @author dsh
	 * @param 改变
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/findProcessInstanceVariables")
	@ResponseBody
	public Object findProcessInstanceVariables(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> obj = new HashMap<String, Object>();
		String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
		try {
			Map<String, Object> result = activitiService.findProcessInstanceVariables(taskId);
			obj.put("data", result);
			obj.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			obj.put(Util.MESSAGE, "查找任务所有变量！");
		} catch (Exception e) {
			obj.put("data", "");
			logger.error("=============[ActivitiController[addAttachments[查找任务所有变量]]]==========", e);
		}
		return obj;
	}
	
	/**
	 * 	改变已读未读状态
	 * @author dsh
	 * @param 改变
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/changeIsProcessInstanceRead")
	public String changeIsProcessInstanceRead(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String taskId = request.getParameter("taskId") == null ? "" : request.getParameter("taskId");
		String result = "";
		try {
			result = "success";
			activitiService.changeIsProcessInstanceRead(taskId);
		} catch (Exception e) {
			result = "fail";
			logger.error("=============[ActivitiController[addAttachments[改变已读未读状态]]]==========", e);
		}
		return result;
	}
	
	/**
	 * 	改变已读未读状态
	 * @author dsh
	 * @param 改变
	 * @return List<Attachment>
	 */
	@RequestMapping(value = "/deleteGlobalFile")
	public int deleteGlobalFile(@RequestBody Map<String, Object> map,HttpServletRequest request) throws Exception {
		int result = 0;
		
		try {
			result = activitiService.deleteGlobalFile((Integer)map.get("id"), (String)map.get("url"));
		} catch (Exception e) {
			logger.error("=============[ActivitiController[addAttachments[删除全局文件成功]]]==========", e);
		}
		return result;
	}
	
	
	
}
